import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import {renderValveOpen, renderConStatus} from '@/utils/utils';

import debounce from 'lodash/debounce';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddMechanical from './AddMechanical'
import request from '@/utils/request';
import Detail from "./Detail";

const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ concentrator_firmwares, loading, global }) => ({
  concentrator_firmwares,
  global,
  loading: loading.models.concentrator_firmwares,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      concentrator_firmwares: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        concentrator_firmwares: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'concentrator_firmwares/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'concentrator_firmwares/changeLoaded',
          });
          dispatch({
            type: 'concentrator_firmwares/changeTableY',
          });
        },
      });

    }
    const that = this;
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'concentrator_firmwares/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'concentrator_firmwares/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'concentrator_firmwares/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          concentrator_firmwares: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }
      },
    });
  };
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      concentrator_firmwares: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="采集器号">
          {getFieldDecorator('number', {
            initialValue: searchParams.number,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="IMEI">
          {getFieldDecorator('imei', {
            initialValue: searchParams.imei,
          })(<Input style={{ width: '150px' }} placeholder="请输入" onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="在线状态">
          {getFieldDecorator('online_status', {
            initialValue: searchParams.online_status,
          })(<Select style={{width:'90px'}}  allowClear={true}>
            <Option value={''}>全部</Option>
            <Option value={'-1'}>离线</Option>
            <Option value={'1'}>在线</Option>
          </Select>)}
        </FormItem>
        <FormItem label="通信平台">
          {getFieldDecorator('platform', {
            initialValue: searchParams.platform,
          })(<Select style={{width:'90px'}}  allowClear={true}>
            <Option value={'电信'}>电信</Option>
            <Option value={'移动'}>移动</Option>
          </Select>)}
        </FormItem>
    {/*    <FormItem label="口径">
          {getFieldDecorator('caliber', {
            initialValue: searchParams.caliber,
          })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        concentrator_firmwares: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
        });

      });
    }
  }
  handleAddMechanical=()=>{
    const formValues = this.configMechanicalFormRef.props.form.getFieldsValue();
    const state = this.configMechanicalFormRef.state;
    const editRecord=this.state.editRecord
    console.log('formValues', formValues);
    let meterskey=[]
    for(let i in formValues){
      let splitKey=i.split('-')
      let len=splitKey.length;
      if(len>=2){
        if(meterskey.indexOf(splitKey[1])<0){
          meterskey.push(splitKey[1])
        }
      }
    }
    console.log('meterskey',meterskey)
    const metersArr=[]
    for(let i=0;i<meterskey.length;i++){
      metersArr.push({
        meter_number:formValues[`index-${meterskey[i]}`],
        initial_value:Number(formValues[`initial_value-${meterskey[i]}`]),
        caliber:formValues[`caliber-${meterskey[i]}`],
        images:state[`port${meterskey[i]}PicArr`]
      })

    }
    console.log('metersArr',metersArr);
    let sendData={
      ...editRecord,
      address:formValues.address,
      concentrator_images: state.concentratorPicArr,
      "config": {
        "platform": editRecord.config.platform,
        "meter_config": metersArr
      }
    }
    console.log('sendData',sendData)
    const that=this;
    return
    this.props.dispatch({
      type: 'concentrator_firmwares/config',
      payload: {
        config: {
          meter_config: metersArr
        },
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改集中器配置成功');
        that.setState({
          configconcentrator_firmwaresModal: false,
        });
        const {
          concentrator_firmwares: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  }
  handleAdd = () => {
    const formValues = this.addconcentrator_firmwaresForm.props.form.getFieldsValue();
    const that=this;
    console.log('formValues',formValues)
    if(!formValues.file||formValues.file.fileList.length===0){
      message.error('请选择文件');
      return false
    }

    var formData = new FormData();
    formData.append("file", formValues.file.file);
    formData.append("per_package_size", formValues.per_package_size);
    formData.append("remark", formValues.remark);
    formData.append("version", formValues.version);
    request(`/concentrator_firmwares`, {
      method: 'POST',
      data: formData
    }).then((response)=> {
      console.log(response);
      if(response.status===200){
        message.success('上传新版本成功')
        const {
          concentrator_firmwares: { searchParams },
        } = that.props;
        that.setState({
          addconcentrator_firmwaresModal:false
        })
        that.handleSearch(searchParams);

      }
    })
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      number: '',
      user_number: '',
      status: '1',
      caliber:'',
      address: '',
      imei:'',
      vendor_id: '',
      page: 1,
      per_page: 50,
    });
  };

  handleEdit = () => {
    const formValues = this.editMechanicalFormRef.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `concentrator_firmwares/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改采集器成功');
        that.setState({
          editconcentrator_firmwaresModal: false,
        });
        const {
          concentrator_firmwares: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `concentrator_firmwares/remove`,
      payload: { id },
      callback: () => {
        message.success('删除版本成功');
        const {
          concentrator_firmwares: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleImport=()=>{
    const formValues =this.importFormRef.props.form.getFieldsValue();
    const that=this;
    console.log('formValues',formValues)
    if(!formValues.file||formValues.file.fileList.length===0){
      message.error('请选择文件');
      return false
    }

    var formData = new FormData();
    formData.append("file", formValues.file.file);
    formData.append("protocol_id", formValues.protocol_id);
    formData.append("start_row", formValues.start_row);
    formData.append("end_row", formValues.end_row);
    request(`/meter_files`, {
      method: 'POST',
      data: formData
    }).then((response)=> {
      console.log(response);
      if(response.status===200){
        message.success('批量导入采集器成功')
        const {
          concentrator_firmwares: { searchParams },
        } = that.props;
        that.setState({
          importModal:false
        })
        that.handleSearch(searchParams);

      }
    })
  }

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case -1:
        type = 'close-circle', color = '#eb2f96', text = '关';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={false}/>;
        break;
      case 1:
        type = 'check-circle', color = '#52c41a', text = '开';
        return <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={true}/>;
        break;
      case 2:
        type = 'close-circle', color = '#fe5810', text = '未上报';
        break;
      case 3:
        type = 'close-circle', color = '#fe1b2e', text = '异常';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      concentrator_firmwares: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username');
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            concentrator_firmwares: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '版本',
        width: 80,
        frozen: true,
        key: 'version',

      },
      {
        name: '文件大小(字节)',
        key: 'file_size',
        width: 120,
      },
      {
        name: '每包大小(字节)',
        key: 'per_package_size',
        width: 120,
      },
      {
        name: '包数量',
        key: 'package_count',
        width: 80,
      },
      {
        name: '校验码',
        key: 'check_code',
        width: 80,
      },
      {
        name: '创建时间',
        key: 'created_at',
        width: 170,
      },
      {
        name: '备注',
        key: 'remark',
        width: 170,
      },
      {
        name: '操作',
        width: 200,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Fragment>
            <Button
              type="primary"
              size="small"
              icon="edit"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  editconcentrator_firmwaresModal: true,
                });
              }
              }
            >编辑
            </Button>
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要删除"${event.row.version}"吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered:true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除
            </Button>

          </Fragment>


        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));
    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>采集器固件列表</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>采集器版本总数量(个)</p>
            <h4>{meta.total}</h4>
          </div>
            <div size="large" className="table-info-right-item">
              <Button
                  icon="plus"
                  style={{marginLeft: 8}}
                  type="primary"
                  onClick={
                    () => {
                      this.setState({
                        addconcentrator_firmwaresModal: true,
                      });
                    }
                  }
                >
                  上传新版本
                </Button>

            </div>


        </div>
        {/* <div className="table-condition">{this.renderSimpleForm()}</div> */}
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (index,row) => {
                if (!row) {
                  return;
                }
                this.props.dispatch({
                  type: 'concentrator_firmwares/changeSelectRow',
                  payload:[index],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          concentrator_firmwares: {  scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop =0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addconcentrator_firmwaresModal} modalClass="addconcentrator_firmwaresModal" title="上传新版本"/>}
        visible={this.state.addconcentrator_firmwaresModal}
        centered
        onOk={()=>{
          that.handleAdd()
        }}
        className="addconcentrator_firmwaresModal"
        onCancel={() => {
          this.setState({ addconcentrator_firmwaresModal: false });
        }}

      >
        <AddMechanical  wrappedComponentRef={(inst) => this.addconcentrator_firmwaresForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editconcentrator_firmwaresModal} modalClass="editconcentrator_firmwaresModal" title="修改版本"/>}
        visible={this.state.editconcentrator_firmwaresModal}
        centered
        destroyOnClose
        onOk={()=>{
          that.handleEdit()
        }}
        className="editconcentrator_firmwaresModal"
        onCancel={() => {
          this.setState({ editconcentrator_firmwaresModal: false });
        }}

      >
        <AddMechanical editRecord={this.state.editRecord}  wrappedComponentRef={(inst) => this.editMechanicalFormRef = inst}/>
      </Modal>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={850}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
